package yl.hs.bmipfull.controllers.production;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.pojo.production.ProductShipOrderEntity;
import yl.hs.bmipfull.service.production.IProductShipOrderService;
import yl.hs.bmipfull.service.system.ISearchViewService;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.DateUtil;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.SubmitModel;
import yl.hs.bmipfull.viewmodels.WebResult;
import yl.hs.bmipfull.viewmodels.production.OrderTransModel;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 作用:  产品发货单控制层<br/>
 * 创建时间: 2021年06月21日 10时08分52秒 <br/>
 *
 * @author 谢东
 */
@Api(value = "产品发货单Web接口", tags = "生产管理——产品发货单操作")
@RequestMapping(value = "/api/productShipOrder")
@RestController
public class ProductShipOrderController extends ControllerBase {

    @Resource
    private IProductShipOrderService service;
    @Autowired
    ISearchViewService svSVC;
    private PageResult<ProductShipOrderEntity> result;
    private PageResult<ProductShipOrderEntity> result1;

    @ApiOperation(value = "查询产品发货单", notes = "查询产品发货单")
    @RequestMapping(value = "/{productCateSn}", method = RequestMethod.POST)
    public WebResult queryList(@ApiParam(value = "查询条件") @RequestBody PageQuery pageQuery,
                               @ApiParam(value = "发货单类型") @PathVariable String productCateSn) {
        try {
            return success("查询成功", service.queryList(pageQuery,productCateSn));
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "查询产品发货单", notes = "分页查询产品发货单")
    @RequestMapping(value = {"/{rowNum}/{page}/{productCateSn}","/{rowNum}/{page}"}, method = RequestMethod.POST)
    public WebResult queryPage(@RequestBody PageQuery query,
                               @ApiParam(value = "页码") @PathVariable int page,
                               @ApiParam(value = "每页条数") @PathVariable int rowNum,@ApiParam(value = "发货单类型") @PathVariable(required = false) String productCateSn) {
        try {
            var data =  service.queryList(query,productCateSn);
            var result = service.queryPage(query, rowNum, page,productCateSn);
            svSVC.updateUserMenuView(query);
            var netweight = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getNetWeight()==null ? 0:s.getNetWeight()).toString())).sum()*100)/100;
            var grossWeight = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getGrossWeight()==null ? 0:s.getGrossWeight()).toString())).sum()*100)/100;
            var tareweight = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getTareWeight()==null ? 0 :s.getTareWeight()).toString())).sum()*100)/100;
            var quantity = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getQuantity()==null ? 0 :s.getQuantity()).toString())).sum()*100)/100;
            var salesVolume = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getSalesVolume()==null ? 0 :s.getSalesVolume()).toString())).sum()*100)/100;
            var shipmentReviewWeight = (double)Math.round(data.stream().mapToDouble(s -> Double.valueOf((s.getShipmentReviewWeight()==null ? 0 :s.getShipmentReviewWeight()).toString())).sum()*100)/100;
            var signedWeight  = data.stream().map(t->(t.getSignedWeight()==null? BigDecimal.ZERO:t.getSignedWeight())).reduce(BigDecimal.ZERO,BigDecimal::add);
            var totalAmount  = data.stream().map(t->t.getAmount()).reduce(BigDecimal.ZERO,BigDecimal::add);
            val map = Tl.toMap(result);
            map.put("netweight",netweight);
            map.put("grossWeight",grossWeight);
            map.put("tareweight",tareweight);
            map.put("quantity",quantity);
            map.put("signedWeight",signedWeight);
            map.put("amount",totalAmount);
            map.put("salesVolume",salesVolume);
            map.put("shipmentReviewWeight",shipmentReviewWeight);
            return success("ok", map);
        } catch (Exception ee) {
            return error(ee);
        }
    }


    @ApiOperation(value = "查询产品发货单", notes = "根据产品发货单编号查询产品发货单")
    @RequestMapping(value = "/{sn}", method = RequestMethod.GET)
    public WebResult findBySn(@ApiParam(value = "编号") @PathVariable String sn) {
        return success("查询成功", service.findBySn(sn));
    }
    @ApiOperation(value = "批量保存签收/审核信息", notes = "批量保存签收/审核信息")
    @RequestMapping(path = "sign/orderShips", method = RequestMethod.POST)
    public WebResult saveSignInfes(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        WebResult res;
        try {
            List<Map<String, Object>> datas = (List<Map<String, Object>>) submitModel.getData().get("orderShips");
            int result = 0;
            if (datas != null && datas.size() > 0) {
                for (var map : datas) {
                    SubmitModel submitModelObj = new SubmitModel();
                    submitModelObj.setSn((String) map.get("sn"));
                    submitModelObj.setData((Map<String, Object>) map.get("data"));
                    result += service.saveSignInfo(submitModelObj);
                }

            }
            if (result > 0) {
                res = success("保存成功");
            } else {
                res = fail("保存失败");
            }
        } catch (Exception ee) {
            res = error(ee);
        }
        return res;
    }

    @ApiOperation(value = "保存产品发货单", notes = "查询/更新产品发货单信息")
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public WebResult saveMenu(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        ProductShipOrderEntity result;
        try {
            result = service.saveProductShipOrder(submitModel.getData(), submitModel.getSn());
            if (result != null) {
                return success("保存成功",result);
            } else {
                return fail("数据未保存",null);
            }
        } catch (Exception e) {
            return error(e);
        }

    }

    @ApiOperation(value = "删除产品发货单信息", notes = "根据产品发货单编号删除系产品发货单信息")
    @RequestMapping(path = "", method = RequestMethod.DELETE)
    public WebResult delete(@ApiParam(value = "产品发货单编号", name = "sn", allowMultiple = true, required = true) @RequestParam("sn") String[] sn) {
        if (service.delete(sn) > 0) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }

    }
    @ApiOperation(value = "根据发货单类型和天数查询单据信息", notes = "根据发货单类型和天数查询单据信息")
    @RequestMapping(path = "/bystate/{orderType}/{time}", method = RequestMethod.GET)
    public WebResult questListByType(@ApiParam(value = "产品类别编号") @PathVariable String productCateSN,@ApiParam(value = "开始日期") @PathVariable Date time){
        return success("查询成功",service.questListByType(productCateSN,time));
    }
    @ApiOperation(value = "保存审核信息", notes = "保存发货单审核信息")
    @RequestMapping(path = "review", method = RequestMethod.POST)
    public WebResult saveReview(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel)
    {
        var result = service.saveReviewOrders(submitModel);
        if(result>0) {
            return success("审核完成");
        }
        else{
            return fail("审核失败");}
    }

    @ApiOperation(value = "保存运费审核信息", notes = "保存发货单运费审核信息")
    @RequestMapping(path = "freightReview", method = RequestMethod.POST)
    public WebResult saveFreightReview(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel)
    {
        var result = service.saveFreightReviewOrders(submitModel);
        if(result>0) {
            return success("审核完成");
        }
        else{
            return fail("审核失败");}
    }

    @ApiOperation(value = "保存签收信息", notes = "保存发货单签收信息")
    @RequestMapping(path = "sign", method = RequestMethod.POST)
    public WebResult saveSignInfo(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel)
    {
        try {
            var result = service.saveSignInfo(submitModel);
            if(result>0) {
                return success("保存成功");
            }
            else{
                return fail("保存失败");
        }}
        catch (Exception ee){
            return  error(ee);
        }
    }

    @ApiOperation(value = "保存审核备注信息", notes = "保存发货单审核备注信息")
    @RequestMapping(path = "reviewFlag", method = RequestMethod.POST)
    public WebResult saveReviewFlag(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel)
    {
        try {
            var result = service.saveReviewFlag(submitModel);
            if(result > 0) {
                return success("保存成功");
            }
            else {
                return fail("保存失败");
            }
        }
        catch (Exception ee){
            return error(ee);
        }
    }
    @ApiOperation(value = "保存运费审核备注信息", notes = "保存发货单运费审核备注信息")
    @RequestMapping(path = "freightReviewFlag", method = RequestMethod.POST)
    public WebResult saveFreightReviewFlag(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel)
    {
        try {
            var result = service.saveFreightReviewFlag(submitModel);
            if(result > 0) {
                return success("保存成功");
            }
            else {
                return fail("保存失败");
            }
        }
        catch (Exception ee){
            return error(ee);
        }
    }
    @ApiOperation(value = "获取发货单照片路径",notes = "获取发货单照片路径")
    @RequestMapping(path = "getpathurl/{sn}")
    public WebResult getPathUrl(@PathVariable String sn){
        try{
        var filePath = HsApp.getSystemSet(CK.UpLoadFilePath);
        File folder = new File(filePath);
            var fileList = new ArrayList<String>();
        if(folder.isDirectory()){
            var files = folder.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {

                    return pathname.getName().contains(sn);
                }
            });

            for (var file:files){
                fileList.add(file.getName());
            }
            return success( "OK",fileList);
        }
        return success("OK", fileList);
        }catch (Exception ee){
            return error(ee);
        }
    }
    @ApiOperation(value = "获取发货单照片",notes = "获取发货单照片")
    @RequestMapping(path = "image/{imgUrl}")
        public void picToJSP(@PathVariable String imgUrl, HttpServletRequest request, HttpServletResponse response){
            FileInputStream in;
            response.setContentType("application/octet-stream;charset=UTF-8");
            try {
                //图片读取路径
                var filePath = HsApp.getSystemSet(CK.UpLoadFilePath);
                imgUrl = filePath+"/"+imgUrl;
                in=new FileInputStream(imgUrl);
                int i=in.available();
                byte[]data=new byte[i];
                in.read(data);
                in.close();
                //写图片
                OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
                outputStream.write(data);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
               error(e);
            }
        }
    @ApiOperation(value = "作废发货单",notes="作废发货单")
    @RequestMapping(path = "invalid/{sn}",method = RequestMethod.POST)
    public WebResult invalidOrder(@PathVariable String sn,@RequestParam String cause){
        try {
            var result = service.invalidOrder(sn, cause);
            if(result>0){
                return success("作废成功");
            }
            else{
                return fail("作废失败");
                }
        }
        catch (Exception ee){
            return error(ee);
        }
    }

    @ApiOperation(value = "恢复入库单", notes = "恢复入库单")
    @PostMapping("restore/{sn}")
    public WebResult restoreOrder(@PathVariable String sn, @RequestParam String cause){
        try{
            var result = service.restore(sn,cause);
            if(result > 0)
                return success("单据已恢复");
            else{
                return fail("恢复失败");
            }
        }
        catch(Exception ee){
            return error(ee);
        }
    }
    @ApiOperation(value = "根据发货单编号修改发货单状态", notes = "根据发货单编号修改发货单状态")
    @RequestMapping(value = "changeStateBySn/{sn}/{state}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult changeStateBySn(@PathVariable String sn,@PathVariable short state) {
        try {
            Integer result = 0;
            if(state==0){
                result=service.changeStateBySN(sn.split(","), (short) 1);
            }else{
                result=service.changeStateBySN(sn.split(","), state);
            }
            if (result > 0) {
                return success("数据已修改");
            } else if (result == -2) {
                return fail("数据修改失败！");
            }
            return fail("没有修改的任何数据");
        } catch (Exception ee) {
            return error(ee);
        }
    }
    @ApiOperation(value = "根据发货单编号修改发货单开票状态", notes = "根据发货单编号修改发货单开票状态")
    @RequestMapping(value = "changeInvoicingStateBySN/{sn}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult changeInvoicingStateBySN(@PathVariable String sn) {
        try {
            Integer result=service.changeInvoicingStateBySN(sn.split(","), (short)1);
            if (result > 0) {
                return success("数据已修改");
            } else if (result == -2) {
                return fail("数据修改失败！");
            }
            return fail("没有修改的任何数据");
        } catch (Exception ee) {
            return error(ee);
        }
    }
    @ApiOperation(value = "获取产品信息价设置时间分组信息", notes = "获取产品信息价设置时间 分组信息")
    @GetMapping("/set-time-group")
    public WebResult getSetTimeGroup(){
        return success("ok", service.getSetTime());
    }

    @ApiOperation(value = "济源国泰发货单上传", notes = "上传发货单信息")
    @PostMapping(value = "/gtUploadOrder")
    public WebResult gtUploadOrder(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        try {
            var norder = service.uploadOrder(submitModel);
            return success("ok", norder);
        }
        catch (Exception ee){
            return error(ee);
        }
    }
    @ApiOperation(value = "济源国泰发货单上传", notes = "上传发货单信息")
    @PutMapping(value = "/gtOrderUpdate/{sn}")
    public WebResult gtOrderState(@ApiParam(value = "发货单号")@PathVariable String sn){
        try {

            var result = service.querySignedOrder(sn);
            return success("ok",result);
        }
        catch (Exception ee){
            return error(ee);
        }
    }

    @ApiOperation(value = "发货单转工地",notes = "发货单转工地")
    @PostMapping("/order_trans")
    public WebResult orderTrans(@RequestBody OrderTransModel transForm){
        try{
            service.saveOrderTrans(transForm);
            return success("ok");
        }
        catch (Exception ee){
            return error(ee);
        }
    }

    /**
     * 发货单统计报表
     *
     * @param type        （1 日报表 2 月报表 3 年报表）
     * @param companyName (国泰 常春藤)
     * @param year
     * @param month
     * @return
     */
    @ApiOperation(value = "发货量统计报表", notes = "发货单统计报表")
    @GetMapping("/weightStatistics/{type}")
    public WebResult weightStatistics(@PathVariable Integer type,
                                      @RequestParam(required = false) String companyName,
                                      @RequestParam(required = false) String year,
                                      @RequestParam(required = false) String month) {
        return success("ok", service.weightStatistics(type, companyName, year, month));

    }


    /**
     * 车辆工地方量统计报表
     *
     * @param companyName
     * @param startDate
     * @param endDate
     * @return
     */
    @ApiOperation(value = "车辆工地方量统计报表", notes = "车辆工地方量统计报表")
    @GetMapping("/projectAndCarOrderStatistics")
    public WebResult projectAndCarOrderStatistics(
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return success("ok", service.projectAndCarOrderStatistics(companyName,
                DateUtil.formatNullStrOrDateStr(startDate),
                DateUtil.formatNullStrOrDateStr(endDate)));
    }
}